package com.edu.danmu;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * 服务器消息的处理器
 */
public class NettyServerHandler extends SimpleChannelInboundHandler<String> {

    //客户端通道组
    private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    //客户端上线
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //添加客户端到通道组
        channels.add(ctx.channel());
        channels.writeAndFlush(ctx.channel().remoteAddress() + "上线了");
        System.out.println(ctx.channel().remoteAddress() + "上线了");
    }

    //客户端下线
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        channels.writeAndFlush(ctx.channel().remoteAddress() + "下线了");
        System.out.println(ctx.channel().remoteAddress() + "下线了");
    }

    //出现异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        channels.writeAndFlush(ctx.channel().remoteAddress() + "出现异常");
        System.out.println(ctx.channel().remoteAddress() + "出现异常");
        ctx.close();
    }

    //收到消息的处理
    @Override
    protected void channelRead0(ChannelHandlerContext cxt, String s) throws Exception {
        System.out.println("服务器收到消息：" + s);
        //向客户端发送消息
//        channelHandlerContext.channel().writeAndFlush("你好！我是服务器!");
        channels.writeAndFlush(cxt.channel().remoteAddress() + "说：" + s);
    }
}
